package cn.lg.soar.system.biz.modules.general.controller;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.mvc.model.MultipartFileDTO;
import cn.lg.soar.system.api.constant.Const;
import cn.lg.soar.system.biz.filetemplate.FileTemplateManager;
import cn.lg.soar.system.biz.filetemplate.LocalFileTemplateImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author luguoxiang 469599794@qq.com
 * @Date: 2025/5/15 11:47
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Tag(name = "本地文件服务")
@RestController
@RequestMapping(Const.LOCAL_FILE_PATH)
public class LocalFileController {

    @Autowired
    private FileTemplateManager fileTemplateManager;

    @Operation(summary = "访问")
    @GetMapping("/{storageId}/**")
    public void access(
            @Parameter(description = "文件仓库id") @PathVariable("storageId") int storageId,
            @Parameter(description = "签名token") @RequestParam(name = "$", required = false) String token,
            HttpServletRequest request
    ) {
        LocalFileTemplateImpl template = (LocalFileTemplateImpl) fileTemplateManager.getTemplate(storageId);
        String requestUri = request.getRequestURI();
        String p = "/" + storageId;
        int index = requestUri.indexOf(p);
        template.download(requestUri.substring(index + p.length() + 1), token);
    }

    @Operation(summary = "上传")
    @PutMapping("/{storageId}/**")
    public ResponseEntity<?> upload(
            @RequestParam(value = "file",required = false) MultipartFile file,
            @Parameter(description = "文件仓库id") @PathVariable("storageId") int storageId,
            @Parameter(description = "签名token") @RequestParam(name = "$", required = false) String token,
            HttpServletRequest request
    ) throws IOException {
        String requestUri = request.getRequestURI();
        String p = "/" + storageId;
        int index = requestUri.indexOf(p);
        String filename = requestUri.substring(index + p.length() + 1);
        // 保存文件
        LocalFileTemplateImpl template = (LocalFileTemplateImpl) fileTemplateManager.getTemplate(storageId);
        if (file == null) {
            file = new MultipartFileDTO("1", request.getInputStream());
        }
        AssertUtil.notNull(file, "请上传文件内容");
        template.upload(file, filename, token);
        // 响应结果
        String etag = "\"" + template.getEtag(filename) + "\"";
        return ResponseEntity.ok()
                .header("ETag", etag)
                .build();
    }

}
